package logic

import (
	"context"
	"errors"
	"hem/models/mysql"

	"hem/hemrpc/hemrpc"
	"hem/hemrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type HemAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHemAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HemAddLogic {
	return &HemAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HemAddLogic) HemAdd(in *hemrpc.HemAddRequest) (*hemrpc.HemAddResponse, error) {
	// todo: add your logic here and delete this line
	var findHem mysql.Hem
	mysql.DB.Debug().Where("title=?", in.Title).Find(&findHem)
	if in.Title == findHem.Title {
		return nil, errors.New("当前商品已存在,不能重复添加")
	}

	hem := mysql.Hem{
		Title: in.Title,
		Image: in.Image,
		Price: float64(in.Price),
		Num:   int(in.Num),
	}
	mysql.DB.Debug().Create(&hem)

	return &hemrpc.HemAddResponse{
		HemId: int64(hem.ID),
	}, nil
}
